package com.xq.tmall.agu.ferign;

import com.alibaba.excel.util.DateUtils;
import com.xq.tmall.agu.job.ITimerJob;
import com.xq.tmall.entity.StockSector;
import com.xq.tmall.entity.StockSectorHistory;
import com.xq.tmall.service.StockSectorHistoryService;
import com.xq.tmall.service.StockSectorService;
import com.xq.tmall.util.DateUtil;
import com.xq.tmall.util.ITimeJobFactory;
import lombok.extern.slf4j.Slf4j;
import org.ehcache.core.internal.util.CollectionUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component("StockSectorHistorySpider")
public class StockSectorHistorySpider implements Runnable {

    @Resource
    private StockSectorHistoryService sectorHistoryService;

    @Resource
    private StockSectorService stockSectorService;

    @Override
    public void run() {
        log.info("StockSectorHistorySpider=======开始执行");
        try {
            // 只保留两个月数据
            Date historyDate = DateUtil.addDay(new Date(), -90);
            sectorHistoryService.historyDelete(DateUtils.format(historyDate, "yyyy-MM-dd"));
            // 判断当前是否已插入，插入后无需插入
            Map<String, Object> params = new HashMap<>();
            params.put("historyDate", DateUtils.format(new Date(), "yyyy-MM-dd"));
            List<StockSectorHistory> stockSectorHistoryList = sectorHistoryService.findStockSectorHistoryList(params);
            if (!CollectionUtils.isEmpty(stockSectorHistoryList)) {
                ITimeJobFactory.getJob(ITimeJobFactory.TIMEJOB.SECTOR_HISTORY).execute(ITimerJob.COMMAND.STOP);
                return;
            }
            List<StockSector> stockSectorList = stockSectorService.findAllStockSectorInfo(new HashMap<>());
            log.info("当前获取股票代码COUNT:" + stockSectorList.size());
            // 插入历史记录
            if(!CollectionUtils.isEmpty(stockSectorList)){
                sectorHistoryService.batchInsert(stockSectorList);
            }
        } catch (Exception e) {
            log.info("批量插入历史股票数据异常:", e);
        }
    }
}
